package com.nidu.demo.user.executor.query;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.user.convertor.UserConvertor;
import com.nidu.demo.user.dto.UserCO;
import com.nidu.demo.user.dto.UserProfileCO;
import com.nidu.demo.user.gateway.UserDepartmentGateway;
import com.nidu.demo.user.gateway.UserGateway;
import com.nidu.demo.user.gateway.UserPositionGateway;
import com.nidu.demo.user.gateway.UserRoleGateway;
import com.nidu.demo.user.model.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@RequiredArgsConstructor
public class UserSingleQryExe {

    private final UserConvertor convertor;

    private final UserGateway userGateway;

    private final UserDepartmentGateway userDeptGateway;

    private final UserPositionGateway userPostGateway;

    private final UserRoleGateway userRoleGateway;

    public SingleResponse<UserCO> execute(Long id) {
        User user = userGateway.getById(id);
        if (user == null) {
            throw new BizException(ErrorCodeConstants.USER_NOT_FOUND.getCode(), ErrorCodeConstants.USER_NOT_FOUND.getMessage());
        }
        //查询角色、部门、职位信息
        this.setProfileInfo(user);

        UserCO userCO = convertor.toClientObject(user);

        return SingleResponse.of(userCO);
    }

    public SingleResponse<UserProfileCO> getProfileById(Long id) {
        User user = userGateway.getById(id);
        if (user == null) {
            throw new BizException(ErrorCodeConstants.USER_NOT_FOUND.getCode(), ErrorCodeConstants.USER_NOT_FOUND.getMessage());
        }
        UserProfileCO userCO = convertor.toUserProfileCO(user);

        return SingleResponse.of(userCO);
    }

    private void setProfileInfo(User user) {
        // 查询角色、部门、职位信息
        Set<Long> roleIds = userRoleGateway.getRoleIdsByUserId(user.getId());
        Set<Long> deptIds = userDeptGateway.getDeptIdsByUserId(user.getId());
        Set<Long> postIds = userPostGateway.getPostIdsByUserId(user.getId());
        user.setProfile(roleIds, deptIds, postIds);
    }

}
